package cn.szq.springframework.beans.factory.support;

import cn.szq.springframework.beans.BeansException;
import cn.szq.springframework.beans.factory.BeanFactory;
import cn.szq.springframework.beans.factory.config.BeanDefinition;
import cn.szq.springframework.beans.factory.config.BeanPostProcessor;
import cn.szq.springframework.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/***
 * All rights Reserved, Designed By www.jx-lab.com
 * @Title: AbstractBeanFactory
 * @Description:
 * @author lixy
 * @date 2021/8/12 8:49
 * @version V1.0
 * @Copyright: www.jx-lab.com Inc. All rights reserved.
 * 注意：本内容仅限于众合景轩信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

    /** BeanPostProcessors to apply in createBean */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();


    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T)getBean(name);
    }

    protected <T> T doGetBean(final String name, final Object[] args){
        Object bean = getSingleton(name);
        if (bean  != null){
            return (T)bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T)createBean(name, beanDefinition, args);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor){
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }
}
